//
//  TrackManager.m
//  taptap-server
//
//  Created by Michael Humphris on 11/08/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "TrackManager.h"

@implementation TrackManager
@synthesize delegate;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

-(void) processDirectory:(NSString *)containingFolder{
    templatesForDifficulty = [[NSMutableDictionary alloc] initWithCapacity:6];
    
    [templatesForDifficulty setObject:[[NSMutableArray alloc] init] forKey:[NSNumber numberWithInt:DAll]];
    [templatesForDifficulty setObject:[[NSMutableArray alloc] init] forKey:[NSNumber numberWithInt:DEasy]];
    [templatesForDifficulty setObject:[[NSMutableArray alloc] init] forKey:[NSNumber numberWithInt:DMedium]];
    [templatesForDifficulty setObject:[[NSMutableArray alloc] init] forKey:[NSNumber numberWithInt:DHard]];
    [templatesForDifficulty setObject:[[NSMutableArray alloc] init] forKey:[NSNumber numberWithInt:DExtreme]];
    
    
    
    workerArgs* args = [[workerArgs alloc] initWithFolder:containingFolder isContainingFolder:YES];
    [self performSelectorInBackground:@selector(DoWork:) withObject:args];
    [args release];
}

-(void)DoWork:(workerArgs *)args{
    NSString *trackPath =@"~/Library/Application Support/TapTapServer/tracks";
    trackPath = [trackPath stringByExpandingTildeInPath];
    
    NSMutableArray *trackPaths = [[NSMutableArray alloc] init];
    if (![args isContainingFolder]) {
        [trackPaths addObject:[args folder]];
    } else {
        [trackPaths addObjectsFromArray:[Filesystem directoriesForPath:[args folder]]];
    }
    
    NSString *masterTemplate = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"default" ofType:@"template"] encoding:NSUTF8StringEncoding error:nil];
    
    
    masterTemplate = [masterTemplate stringByReplacingOccurrencesOfString:@"[authenticated]" withString:[args AccountName]];
    masterTemplate = [masterTemplate stringByReplacingOccurrencesOfString:@"[authenticated_id]" withString:[args AccountID]];
    //NSLog(@"Current masterTemplate: %@",masterTemplate);
        
    
    uint count=0;
    for(NSString *pathToTrack in trackPaths){
        if (![self isValidTrack:pathToTrack]) {
            NSLog(@"Invalid Track Detected! Continuing");
            continue;
        }
        
        NSDictionary* info = [NSDictionary dictionaryWithContentsOfFile:[Path Combine:pathToTrack path2:@"info.plist"]];                
        NSString *errorDesc = nil;
        NSPropertyListFormat format;
        NSDictionary * trackInfo = (NSDictionary*)[NSPropertyListSerialization
                                              propertyListFromData:[info objectForKey:@"data"]
                                              mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                              format:&format
                                              errorDescription:&errorDesc];
        
        
        NSString *trackTemplate = [self makeTrackTemplate:trackInfo];
        
        for (NSNumber *level in [trackInfo objectForKey:@"availableDifficultyLevels"]){
            [[templatesForDifficulty objectForKey:level] addObject:trackTemplate];
        }
        [[templatesForDifficulty objectForKey:[NSNumber numberWithInt:DAll]] addObject:trackTemplate];
        
        
        NSString *savePath = [Path Combine:trackPath path2:[trackInfo objectForKey:@"kTTRDownloadableItemUniqueIdentifierKey"]];
        //NSLog(@"saving to path: %@", savePath);
        
        [self copyFiles:pathToTrack savePath:savePath];
        
        
        //update progress
        count++;
        float progress = ((float)count / (float)[trackPaths count]) * (float)100;
        [delegate updateProgress:progress sender:self];
    }
    
    for (NSNumber *difficulty in [templatesForDifficulty allKeys]){
        NSString *template;
        
        if ([[templatesForDifficulty objectForKey:difficulty] count] == 1) {
            template = @"<key>song</key>";
        } else {
            template = @"<key>songs</key><array>";
        }
        
        for (NSString *trackData in [templatesForDifficulty objectForKey:difficulty]){
            template = [template stringByAppendingString:trackData];
            template = [template stringByAppendingString:@"\n"];
        }
        if ([[templatesForDifficulty objectForKey:difficulty] count] != 1) {
            template = [template stringByAppendingString:@"</array>"];
        }
        
        NSString* plistDir = @"~/Library/Application Support/TapTapServer/";
        plistDir = [plistDir stringByExpandingTildeInPath];

        
        
        if (![Filesystem directoryExists:plistDir]) {
            [Filesystem createDirectory:plistDir];
        }
                
        NSString* templateSavePath = [Path Combine:plistDir path2:([NSString stringWithFormat: @"%i.plist",[difficulty intValue]])];
        
        
        template = [masterTemplate stringByReplacingOccurrencesOfString:@"[songInfos]" withString:template];
        
        
        
        if([template writeToFile:templateSavePath atomically:YES encoding:NSUTF8StringEncoding error:nil]){
            //NSLog(@"Template for difficulty: %@ saved to: %@",difficulty,templateSavePath);
        } else {
            NSLog(@"error saving template");
        }
    }
    [delegate workDone:self];
}

-(NSString*)makeTrackTemplate:(NSDictionary *)trackInfo{    
    NSMutableArray *downloadableCommands = [trackInfo objectForKey:@"kTTRDownloadableItemCommandsKey"];
    //NSLog(@"trackInfo: %@",[trackInfo description]);

    NSString *ThemeAddr = @"http://pub.tapulous.com/themes";
    NSString *TrackAddr = @"http://pub.tapulous.com/tracks";
    
    
    
    NSString* trackID = [trackInfo objectForKey:@"kTTRDownloadableItemUniqueIdentifierKey"];
    for (NSMutableDictionary *downloadObj in downloadableCommands) {
        if ([downloadObj objectForKey:@"kTTRDownloadableItemPreferredFilenameKey"] != nil) {
            //Is part of the track
            NSString *requestedFilename = [downloadObj objectForKey:@"kTTRDownloadableItemPreferredFilenameKey"];
            
            NSURL *newURL = [NSURL URLWithString:TrackAddr];
            newURL = [newURL URLByAppendingPathComponent:trackID isDirectory:YES];
            newURL = [newURL URLByAppendingPathComponent:requestedFilename];
            
            [downloadObj setObject:[NSString stringWithFormat:@"%@",newURL] forKey:@"kTTRDownloadableItemSourceURLKey"];
            
        } else {
            //Is reference to the theme
            NSString *themeName = [[[downloadObj objectForKey:@"kTTRDownloadableItemDependencyKey"] lastPathComponent] stringByDeletingPathExtension];
            NSString *themeVersion = [downloadObj objectForKey:@"kTTRDownloadableItemVersionKey"];
            
            NSURL *newURL = [NSURL URLWithString:ThemeAddr];
            newURL = [newURL URLByAppendingPathComponent:[themeName stringByAppendingString:@"Bundle"]];
            newURL = [newURL URLByAppendingPathComponent:[NSString stringWithFormat:@"v%@",themeVersion]];
            newURL = [newURL URLByAppendingPathComponent:[themeName stringByAppendingString:@".ttrTheme.zip"]];
            
            [downloadObj setObject:[NSString stringWithFormat:@"%@",newURL] forKey:@"kTTRDownloadableItemSourceURLKey"];
        }

    }
    
    
    
    [trackInfo setValue:downloadableCommands forKey:@"kTTRDownloadableItemCommandsKey"];
    //NSLog(@"trackInfo Final: %@",[trackInfo description]);
    
    NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:trackInfo format:kCFPropertyListXMLFormat_v1_0 errorDescription:nil];
    
    NSString *retVal = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
    
    
    retVal = [retVal stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" withString:@""];
    retVal = [retVal stringByReplacingOccurrencesOfString:@"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" withString:@""];
    retVal = [retVal stringByReplacingOccurrencesOfString:@"<plist version=\"1.0\">" withString:@""];
    retVal = [retVal stringByReplacingOccurrencesOfString:@"</plist>" withString:@""];

    return [retVal autorelease];
}

-(BOOL)isValidTrack:(NSString *)pathToTrack{
    NSLog(@"isValidTrack not implimented");
    return YES;
}

-(void) copyFiles:(NSString *)pathToTrack savePath:(NSString *)savePath{
    if (![Filesystem directoryExists:savePath]) {
        [Filesystem createDirectory:savePath];
    }
    
    for (NSString* file in [Filesystem filesInDirectory:pathToTrack isRecursive:YES]){
        NSString *destName = [Path Combine:savePath path2:[file stringByReplacingOccurrencesOfString:pathToTrack withString:@""]];
        [[NSFileManager defaultManager] copyItemAtPath:file toPath:destName error:nil];
    }
}

-(void)dealloc{
    
    for(NSObject *obj in templatesForDifficulty){
        [obj release];
    }
        
    [templatesForDifficulty release];
}

@end
